//
//  EmoticonBoard.swift
//  KeyBoard
//
//  Created by mac on 15/12/26.
//  Copyright © 2015年 mac. All rights reserved.
//

import UIKit

private let toolBarHeight: CGFloat = 35
private let EmoticonCellId = "EmoticonCellId"
class EmoticonBoard: UIView {
    //设置模型数组
    private lazy var packages = EmoticonManager.sharedEmoticonManager.packages
    //色织代理
    var selectEmoticonBlock: ((em: Emoticons) -> ())?
    
    init(selecteEmoticon:(em: Emoticons) -> ()) {
        self.selectEmoticonBlock = selecteEmoticon
        let rect = CGRect(x: 0, y: 0, width: UIScreen.mainScreen().bounds.size.width, height: 220)
        super.init(frame: rect)
        backgroundColor = UIColor.whiteColor()
        //设置ui
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    //设置ui
    private func setupUI() {
        //设置ui
        addSubview(toolBar)
        addSubview(collection)
        toolBar.snp_makeConstraints { (make) -> Void in
            make.bottom.left.right.equalTo(self)
            make.height.equalTo(toolBarHeight)
        }
        collection.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(toolBar.snp_top)
            make.top.left.right.equalTo(self)
        }
        //设置toolBar
        setToolBar()
    }
    private func setToolBar() {
        toolBar.tintColor = UIColor.lightGrayColor()
        var items = [UIBarButtonItem]()
        var index = 0
        for p in packages {
            let item = UIBarButtonItem(title: p.group_name_cn, style: .Plain, target: self, action: "itemDidClick:")
            items.append(item)
            items.last?.tag = index++
            //创建弹簧
            let space = UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil)
            items.append(space)
        }
        items.removeLast()
        toolBar.items = items
    }
    
    //按钮点击事件
    @objc private func itemDidClick(item:UIBarButtonItem) {
        let indexpath = NSIndexPath(forItem: 0, inSection: item.tag)
        collection.scrollToItemAtIndexPath(indexpath, atScrollPosition: .Left, animated: true)
    }
    
    //懒加载
    private lazy var toolBar:UIToolbar = UIToolbar()
    private lazy var collection: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        //设置item的宽度
        let w = UIScreen.mainScreen().bounds.width / 7
        layout.itemSize = CGSizeMake(w, w)
        layout.minimumLineSpacing = 0
        layout.minimumInteritemSpacing = 0
        layout.scrollDirection = .Horizontal
        let margin = (self.bounds.height - toolBarHeight - 3 * w) / 4
        layout.sectionInset = UIEdgeInsets(top: margin, left: 0, bottom: margin, right: 0)
        let collection = UICollectionView(frame: CGRectZero, collectionViewLayout: layout)
        collection.delegate = self
        collection.dataSource = self
        //注册cell
        collection.registerClass(EmoticonCell.self, forCellWithReuseIdentifier: EmoticonCellId)
        //翻页设置
        collection.pagingEnabled = true
        collection.backgroundColor = UIColor.whiteColor()
        return collection
    }()

}

extension EmoticonBoard:UICollectionViewDataSource,UICollectionViewDelegate {
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return packages.count
    }
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return packages[section].emoticones.count
    }
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        //注册cell
        let cell = collection.dequeueReusableCellWithReuseIdentifier(EmoticonCellId, forIndexPath: indexPath) as! EmoticonCell
        cell.emoticones = packages[indexPath.section].emoticones[indexPath.item]
        return cell
    }
    //选中的那个item
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        let em = packages[indexPath.section].emoticones[indexPath.item]
        self.selectEmoticonBlock?(em: em)
    }
    
}

//cell
class EmoticonCell:UICollectionViewCell {
    //设置属性
    var emoticones :Emoticons? {
        didSet{
            emoticonBtn.setImage(UIImage(contentsOfFile:emoticones?.imagePath ?? ""), forState: .Normal)
            emoticonBtn.setTitle(emoticones?.codeStr ?? "", forState: .Normal)
            
            if let em = emoticones where em.isDelete {
                emoticonBtn.setImage(UIImage(named: "compose_emotion_delete"), forState: .Normal)
            }
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        //设置UI
        setupUI()
        self.backgroundColor = UIColor.whiteColor()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    private func setupUI() {
        addSubview(emoticonBtn)
        emoticonBtn.backgroundColor = UIColor.whiteColor()
        emoticonBtn.frame = CGRectInset(bounds, 4, 4)
        emoticonBtn.titleLabel?.font = UIFont.systemFontOfSize(32)
        //让btn失去交互
        emoticonBtn.userInteractionEnabled = false
    }
    //懒加载
    lazy var emoticonBtn:UIButton = UIButton()
}



